package cn.zyq.charging.order.exception;

import cn.zyq.charging.common.pojo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;

/**
 * 全局统一异常处理器 (本类要和controller类平级<不能放到controller的上一级>)
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 用来处理异常MethodArgumentNotValidException
     * (处理视图页面提交给controller数据不能通过springvalidation框架的异常)
     * @param e
     * @return
     */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("捕获了MethodArgumentNotValidException异常", e.getMessage());
        //FieldError fieldError = e.getFieldError();
        //String defaultMessage = fieldError.getDefaultMessage();

        //StringBuffer是线程安全的(StringBuilder不安全)
        StringBuffer allMessage = new StringBuffer();
        List<FieldError> fieldErrors = e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            allMessage.append(defaultMessage);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(4000);
        jsonResult.setMessage(allMessage.toString());
        return jsonResult;
    }
}
